package cn.edu.hznu.mybatis.sqlsession.impl;

import cn.edu.hznu.mybatis.config.Configuration;
import cn.edu.hznu.mybatis.sqlsession.SqlSession;
import cn.edu.hznu.mybatis.proxy.MapperProxy;
import cn.edu.hznu.mybatis.utils.DataSourceUtil;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by wjj on 2020/5/25
 */
public class SqlSessionImpl implements SqlSession {
    private Configuration cfg;
    private Connection connection;

    public SqlSessionImpl(Configuration cfg) {
        this.cfg = cfg;
        this.connection= DataSourceUtil.getConnection(cfg);
    }

    public <T> T getMapper(Class<T> daoInterfaceClass) {
        return (T)Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
                new Class[]{daoInterfaceClass},
                new MapperProxy(cfg, connection)
        );

    }

    public void close() {
            if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
